package cn.chinaunicom.cyhlw.web.oauthServer.support.security;

import cn.chinaunicom.cyhlw.facade.userCenter.entity.UserInfo;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 * 用于集成spring security
 * </p>
 *
 * @author wws
 * @since 2018-12-28
 */
@Data
@Accessors(chain = true)
public class LoginUserInfo implements UserDetails {

    private UserInfo userInfo;

    public LoginUserInfo(UserInfo userInfo) {
        this.userInfo = userInfo;
    }

    @Override
    public String getPassword() {
        return userInfo.getPassword();
    }

    @Override
    public String getUsername() {
        return userInfo.getUsername();
    }

    private static final long serialVersionUID = 1L;

    List<GrantedAuthority> grantedAuthorities = new ArrayList<>();

    /**
     * 这要注意，有个坑：必须ROLE 打头（标签，具体方法看类SecurityExpressionRoot），
     *
     * @return
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {


/*            List<Role> roles = userInfo.getRoles();
            if (roles != null && roles.size() > 0) {
                for (Role role : roles) {
                    grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_"+ role.getRoleName()));
                }
            }

            List<Priv> privs = userInfo.getPrivs();
            if (privs != null && privs.size() > 0) {
                for (Priv priv : privs) {
                    grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_PRIV_"+priv.getPrivName()));
                }
            }

             //获取按钮权限
            List<Resource> resources = userInfo.getResources();
            if (resources != null && resources.size() > 0) {
                for (Resource re : resources) {
                    grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_BTN_"+re.getBtnPermission()));
                }
            }*/
        grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_USER"));
        return grantedAuthorities;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return userInfo.isEnabled();
    }
}
